package com.cjc.ziputil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

import com.cjc.ziputil.tools.CompresszZipFile;
/**
 * 
 *****************************************************
 * <hr>
 * <dt><span class="strong">类功能简介:</span></dt>
 * <dd>Coffee</dd>
 * <dt><span class="strong">创建时间:</span></dt>
 * <dd>2015-3-12 下午2:16:58</dd>
 * <dt><span class="strong">公司:</span></dt>
 * <dd>拷贝文件到sd卡并解压到相应的目录</dd>
 * @author aa1000777 - Email:aa1000777@qq.com
 *****************************************************
 */
public class MainActivity extends Activity {
	Button mBtn_zip;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
	}

	private void initView() {
		// TODO Auto-generated method stub
		mBtn_zip = (Button) findViewById(R.id.mBtn_zip);
		mBtn_zip.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				copyAndZip();
			}
		});
	}

	/**
	 * 
	 ***************************************************** 
	 * 方法简介: 拷贝文件到sd卡并解压到相应的目录
	 ***************************************************** 
	 */
	protected void copyAndZip() {
		// TODO Auto-generated method stub
		File f = Environment.getExternalStorageDirectory();// 获取SD卡目录
		File file = new File(f, "ZipUtil/");// 读sdcard文件
		System.out.println("看下文件路径：" + file.getPath());
		if (!file.exists()) {
			try {
				// 创建目录
				file.mkdir();
				// sd卡中文件的完整路径
				String zipFileName = file.getPath() + "/ZipUtil.zip";
				// copy文件到sd卡
				copyBigDataToSD(zipFileName);
				CompresszZipFile zip = new CompresszZipFile();
				// 解压zip文件到file.getPath()目录
				zip.ReadZip(zipFileName, file.getPath());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	/**
	 * 
	 ***************************************************** 
	 * 方法简介: 拷贝assets文件夹中的文件到sd卡
	 * 
	 * @param strOutFileName
	 *            sd卡中文件的完整路径
	 * @throws IOException
	 ***************************************************** 
	 */
	private void copyBigDataToSD(String strOutFileName) throws IOException {
		InputStream myInput;
		OutputStream myOutput = new FileOutputStream(strOutFileName);
		myInput = this.getAssets().open("ZipUtil.zip");
		byte[] buffer = new byte[1024];
		int length = myInput.read(buffer);
		while (length > 0) {
			myOutput.write(buffer, 0, length);
			length = myInput.read(buffer);
		}
		myOutput.flush();
		myInput.close();
		myOutput.close();
	}
}
